package com.sea.supply.controller;


import com.sea.supply.entity.DistributePlan;
import com.sea.supply.entity.DistributeSku;
import com.sea.supply.service.DistributePlanService;
import com.sea.supply.service.DistributeSkuService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/supply/distribute")
public class DistributeController {

    @Autowired
    private DistributePlanService distributePlanService;
    @Autowired
    private DistributeSkuService distributeSkuService;

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {

        return "/sea/supply/distribute/main";
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     DistributePlan distributePlan) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<DistributePlan> list = distributePlanService.findByCnd(distributePlan);
        PageInfo<DistributePlan> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    @ResponseBody
    @RequestMapping("/findByPlanId")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Integer planId) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<DistributeSku> list = distributeSkuService.findByPlanId(planId);
        PageInfo<DistributeSku> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    @RequestMapping("/detail")
    public String detail(Model model,@RequestParam("planId")Integer id) {
        model.addAttribute("planId",id);
        return "/sea/supply/distribute/detail";
    }


    /**
     * 新增
     * @param distributePlan
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(DistributePlan distributePlan) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        if (null != distributePlan && distributePlanService.save(distributePlan) > 0) {
            result.setOk(true).setMsg("保存成功！");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getDetail", method = RequestMethod.POST)
    public AjaxReturn getDetail(@RequestParam("createId")Integer createId) {
        AjaxReturn result = Ajax.fail().setMsg("获取失败！");
        try{
            distributePlanService.getDetail(createId);
            result.setOk(true).setMsg("获取成功！");
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }

        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/reload", method = RequestMethod.POST)
    public AjaxReturn reload(@RequestParam("planId")Integer planId,@RequestParam("createId")Integer createId) {
        AjaxReturn result = Ajax.fail().setMsg("获取失败！");
        try{
            distributeSkuService.deleteByPlanId(planId);
            distributePlanService.getDetail(createId);
            result.setOk(true).setMsg("获取成功！");
        }catch (RuntimeException e){
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }




    /**
     * 导出当前数据
     * @param response
     * @param CreateDespatchPlan
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestParam("planId") Integer planId)
    {
        List<DistributeSku> list = distributeSkuService.findByPlanId(planId);
        String[] title = {
                "PO","供应商","渠道","SKU","商品名称","颜色","尺码(CM)","尺码(INCH)","可分配数量","预计交期","合同号","装箱量"};
        String fileName = "分配报表" + org.apache.http.client.utils.DateUtils.formatDate(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "分配报表";
        String[][] content = new String[list.size()][12];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            DistributeSku map = list.get(i);
            content[i][0] = map.getReceiveNo();
            content[i][1] = map.getProduceSupplierName();
            content[i][2] = map.getReceiveChannelName();
            content[i][3] = map.getReceiveSku();
            content[i][4] = map.getProductName();
            content[i][5] = map.getProductColorName();
            content[i][6] = map.getProductCm();
            content[i][7] = map.getProductInch();
            content[i][8] = map.getReceiveNumber()+"";
            content[i][9] = null==map.getOrderDate()?"":map.getOrderDate();
            content[i][10] = map.getProduceAgreement();
            content[i][11] = null==map.getCreatePackage()?"0":map.getCreatePackage()+"";

        }
        //创建HSSFWorkbook 艾弗森
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
